#ifndef __LOG_HPP__
#define __LOG_HPP__

#include <iostream>
#include <cstdio>
#include <string>
#include <fstream>
#include <sstream>
#include <memory>
#include <filesystem> //C++17,用于文件系统操作
#include <unistd.h>
#include <time.h>
#include "Mutex.hpp"

namespace LogModule
{
    using namespace LockModule;
    using std::cout;
    using std::endl;
    using std::ofstream;
    using std::string;

    string CurrentTime()
    {
        time_t t = time(nullptr);
        struct tm curr;
        localtime_r(&t, &curr);
        char buf[128];
        strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &curr);
        return buf;
    }

    const string default_log_path = "./log/";
    const string default_log_name = "log.txt";

    enum class LogLevel
    {
        DEBUG = 1, // 调试
        INFO,      // 信息
        WARNING,   // 警告
        ERROR,     // 错误
        FATAL      // 致命错误
    };

    string LogLevelToString(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARNING:
            return "WARNING";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "UNKNOWN";
        }
    }

    // 日志策略 基类
    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;
        virtual void SyncLog(const string &message) = 0; // 同步日志
    };

    // 日志策略 控制台
    class ConsoleLogStrategy : public LogStrategy
    {
    public:
        ConsoleLogStrategy()
        {
        }
        ~ConsoleLogStrategy()
        {
        }
        void SyncLog(const string &message)
        {
            LockGuard lockguard(_lock);
            cout << message << endl;
        }

    private:
        Mutex _lock;
    };

    // 日志策略 文件
    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const string &logpath = default_log_path, const string &logname = default_log_name)
            : _logpath(logpath),
              _logname(logname)
        {
            LockGuard lockguard(_lock);

            if (std::filesystem::exists(_logpath))
            {
                return;
            }
            try
            {
                std::filesystem::create_directories(_logpath);
            }
            catch (std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << "\n";
            }
        }
        ~FileLogStrategy()
        {
        }
        void SyncLog(const std::string &message)
        {
            LockGuard lockguard(_lock);
            string log = _logpath + _logname;
            ofstream out(log, std::ios::app); // 日志写入，追加
            if (!out.is_open())
            {
                return;
            }
            out << message << "\n";
            out.close();
        }

    private:
        string _logpath;
        string _logname;
        Mutex _lock;
    };

    // 日志类: 构建日志字符串, 根据策略进行刷新
    class Logger
    {
    public:
        Logger()
        {
            // 默认采用ConsoleLogStrategy策略
            _strategy = std::make_shared<ConsoleLogStrategy>();
        }
        void EnableConsoleLog()
        {
            _strategy = std::make_shared<ConsoleLogStrategy>();
        }
        void EnableFileLog()
        {
            _strategy = std::make_shared<FileLogStrategy>();
        }
        ~Logger() {}
        
        //日志信息 内部类
        // 示例 [2024-08-04 12:27:03] [DEBUG] [202938] [main.cc] [16] + 日志的可变部分(<< "hello world" << 3.14 << a << b;)
        class LogMessage
        {
        public:
            LogMessage(LogLevel level, const std::string &filename, int line, Logger &logger)
                : _currtime(CurrentTime()),
                  _level(level),
                  _pid(::getpid()),
                  _filename(filename),
                  _line(line),
                  _logger(logger)
            {
                std::stringstream ssbuffer;
                ssbuffer << "[" << _currtime << "] "
                         << "[" << LogLevelToString(_level) << "] "
                         << "[" << _pid << "] "
                         << "[" << _filename << "] "
                         << "[" << _line << "] - ";
                _loginfo = ssbuffer.str();
            }

            template <typename T>
            LogMessage &operator<<(const T &info)
            {
                std::stringstream ss;
                ss << info;
                _loginfo += ss.str();
                return *this;
            }

            ~LogMessage()
            {
                if (_logger._strategy)
                {
                    _logger._strategy->SyncLog(_loginfo);
                }
            }

        private:
            string _currtime; // 当前日志的时间
            LogLevel _level;  // 日志等级
            pid_t _pid;       // 进程pid
            string _filename; // 源文件名称
            int _line;        // 日志所在的行号
            Logger &_logger;  // 负责根据不同的策略进行刷新
            string _loginfo;  // 一条完整的日志记录
        };

        // 就是要拷贝,故意的拷贝
        LogMessage operator()(LogLevel level, const string &filename, int line)
        {
            return LogMessage(level, filename, line, *this);
        }

    private:
        std::shared_ptr<LogStrategy> _strategy; // 日志刷新的策略方案
    };

    Logger logger;

#define LOG(Level) logger(Level, __FILE__, __LINE__)
#define ENABLE_CONSOLE_LOG() logger.EnableConsoleLog()
#define ENABLE_FILE_LOG() logger.EnableFileLog()

}

#endif // __LOG_HPP__